package networklogic

import (
	"context"
	"encoding/json"

	"go-zero-admin/apps/modules/iot/cmd/link/network"
	"go-zero-admin/apps/modules/iot/cmd/link/network/constant"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type UpNetWorkStateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpNetWorkStateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpNetWorkStateLogic {
	return &UpNetWorkStateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpNetWorkStateLogic) UpNetWorkState(in *iotpb.UpNetWorkStateReq) (*iotpb.UpNetWorkStateResp, error) {
	one, err := l.svcCtx.IotNetworkModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update network state"), err, in)
	}

	one.State = in.GetState()
	one.UpdateUser = in.GetUpdateUser()

	// 更新数据
	if err = l.svcCtx.IotNetworkModel.Trans(l.ctx, func(context context.Context, session sqlx.Session) error {
		/// 启动或者关闭网络组件
		iNetworkType := new(network.NetworkType)
		networkType := iNetworkType.Of(one.Type)

		if in.GetState() == constant.NetworkStateOpen {
			// 转化配置
			var config map[string]any
			e := json.Unmarshal([]byte(one.Configuration), &config)
			if e != nil {
				return errors.Wrapf(xerr.NewErrMsg("更新网络组件状态失败：配置转换错误"),
					tool.GetErrMsgFormat("update network state"), e, in)
			}

			// reload网络组件
			e = network.INetworkManager.Reload(networkType, &network.NetworkProperties{
				Id:             in.GetId(),
				Name:           one.Name,
				Enabled:        in.GetState() == constant.NetworkStateOpen,
				Type:           one.Type,
				Configurations: config,
			}, in.GetId())
			if e != nil {
				return errors.Wrapf(xerr.NewErrMsg("更新网络组件状态失败：网络组件开启/关闭错误，请检查配置"),
					tool.GetErrMsgFormat("update network state"), e, in)
			}
		} else if in.GetState() == constant.NetworkStateClose {
			network.INetworkManager.Shutdown(networkType, in.GetId())
		}

		// 更新原本数据
		e := l.svcCtx.IotNetworkModel.UpdateEx(l.ctx, session, one)
		if e != nil {
			return errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
				tool.GetErrMsgFormat("update network state"), err, in)
		}
		return nil
	}); err != nil {
		return nil, err
	}

	return &iotpb.UpNetWorkStateResp{}, nil
}
